package hu.myai.util;

import hu.myai.api.tick.TickProviderInterface;
import hu.myai.api.triggers.TriggerInterface;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.xml.XmlBeanFactory;

public class CommonUtil {

	/**
	 * parse a date
	 */
	synchronized public static Date parseDate(String date) {

		try {
			SimpleDateFormat formatter = new SimpleDateFormat(Constans.dateFormat);
			return formatter.parse(date);

		} catch (ParseException ex) {
			throw new RuntimeException("Error - cannot parse the date: " + date + " (" + Constans.dateFormat + ")");
		}

	}

	/**
	 * get the ticks from the factory and start all of them
	 * */
	synchronized public static void startTicks(XmlBeanFactory factory) {
		// get names of tick providers from Spring configuration
		String[] ticks = factory.getBeanNamesForType(TickProviderInterface.class);

		// initialize each tick provider
		for (String tickName : ticks) {
			factory.getBeansOfType(TriggerInterface.class);

			// get all tick provider instance
			TickProviderInterface tick = (TickProviderInterface) factory.getBean(tickName);

			// start to delegate tick data to the registered components
			// (configuration is in spring xml)
			tick.start();
		}
	}

	@SuppressWarnings("unchecked")
	synchronized public static void removeNull(List list) {
		// apply the remove
		while (list.contains(null)) {
			list.remove(null);
		}
	}
}
